<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS019-全选案例</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        background-color: #222;
        color: snow;
    }

    ul {
        list-style: none;
    }

    table {
        border-collapse: collapse;
    }

    th,
    td {
        border: 1px solid snow;
        padding: .25rem 1rem;
        text-align: center;
    }

    tr td:nth-child(1) {
        text-align: left;
    }

    input[type="checkbox"] {
        width: 1rem;
        height: 1rem;
    }

    .container {
        border: 1px solid gray;
        display: inline-flex;
        flex-direction: column;
        margin: 1rem;
        padding: 1rem;
    }
</style>

<body>
    <div class="container">
        <table>
            <tr>
                <th><input class="check-all" type="checkbox"></th>
                <th>商品</th>
                <th>商家</th>
                <th>价格</th>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>小米手机</td>
                <td>小米</td>
                <td>¥1999</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>小米净水器</td>
                <td>小米</td>
                <td>¥4999</td>
            </tr>
            <tr>
                <td><input type="checkbox"></td>
                <td>小米电视</td>
                <td>小米</td>
                <td>¥5999</td>
            </tr>
        </table>
    </div>

    <script>
        const checkboxAll = document.querySelector('.check-all')
        const checkboxes = document.querySelectorAll('input[type="checkbox"]:not(.check-all)')

        checkboxAll.addEventListener('input', function (e) {
            checkboxes.forEach(checkbox => checkbox.checked = this.checked)
        })

        checkboxes.forEach(checkbox => checkbox.addEventListener('input', function (e) {
            checkboxAll.checked = checkboxes.length === document.querySelectorAll('input[type="checkbox"]:not(.check-all):checked').length
        }))
    </script>
</body>

</html>